import Vue from 'vue'
import { getFileType } from './types'

export const transferFormData = (obj, formData) => {
  const data = []
  if (obj instanceof Array) {
    for (let j = 0, len = obj.length; j < len; j++) {
      const arr = transferFormData(obj[j])
      for (let k = 0, l = arr.length; k < l; k++) {
        const key = formData ? j + arr[k].key : '[' + j + ']' + arr[k].key
        data.push({ key: key, value: arr[k].value })
      }
    }
  } else if (typeof obj === 'object') {
    for (const j in obj) {
      if (obj[j] !== null && obj[j] !== undefined) {
        const arr = transferFormData(obj[j])
        for (let k = 0, l = arr.length; k < l; k++) {
          const key = formData ? j + arr[k].key : '.' + j + '' + arr[k].key
          data.push({ key: key, value: arr[k].value })
        }
      }
    }
  } else {
    data.push({ key: '', value: obj })
  }
  if (formData) {
    // 封装
    for (let i = 0, len = data.length; i < len; i++) {
      formData.append(data[i].key, data[i].value)
    }
  } else {
    return data
  }
}

// formFata转化
export const makeFormData = (object) => {
  const form = new FormData()
  transferFormData(object, form)
  return form
}

export function formatNumber (n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}

// 转为百分号，保留小数点
export function toPercent (num, total) {
  return Math.round((parseFloat(num) / parseFloat(total)) * 10000) / 100.0 + '%' // 小数点后两位百分比
}

// 金额格式化
export function toThousands (num) {
  let result = ''
  let counter = 0
  const numStr = (num || 0).toString()
  const numArr = numStr.split('.')
  num = numArr[0]
  for (var i = numArr[0].length - 1; i >= 0; i--) {
    counter++
    result = numArr[0].charAt(i) + result
    if (!(counter % 3) && i !== 0) {
      result = ',' + result
    }
  }
  return result + (numArr[1] ? '.' + numArr[1].substring(0, 2) : '.00')
}

function strToUnix (time) {
  const date = '2019/01/01 ' + time
  return new Date(date).getTime()
}

// 根据数组对象属性进行排序
export const sortByProperty = (property, type) => {
  return function (a, b) {
    if (type === 'time') {
      return strToUnix(a[property]) - strToUnix(b[property])
    }
    return a[property] - b[property]
  }
}

// 完成将 toChineseNum， 可以将数字转换成中文大写的表示，处理到万级别，例如 toChineseNum(12345)，返回 一万二千三百四十五。
export const toChinesNum = (num) => {
  const changeNum = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九']
  const unit = ['', '十', '百', '千', '万']
  num = parseInt(num)
  const getWan = (temp) => {
    const strArr = temp.toString().split('').reverse()
    let newNum = ''
    for (var i = 0; i < strArr.length; i++) {
      newNum = (i === 0 && strArr[i] === 0 ? '' : (i > 0 && strArr[i] === 0 && strArr[i - 1] === 0 ? '' : changeNum[strArr[i]] + (strArr[i] === 0 ? unit[0] : unit[i]))) + newNum
    }
    return newNum
  }
  const overWan = Math.floor(num / 10000)
  let noWan = num % 10000
  if (noWan.toString().length < 4) noWan = '0' + noWan
  return overWan ? getWan(overWan) + '万' + getWan(noWan) : getWan(num)
}

/**
 * 自动加载对应的模块
 * @param {Object} r 通过 require.context 加载的模块
 */
export const importAll = r => {
  const caches = {}
  // eslint-disable-next-line no-return-assign
  r.keys().forEach(key => {
    // 截取路径作为组件名(必须是文件夹形式)
    const storeName = r(key)?.default?.moduleName
    const pageName = r(key)?.default?.name
    const compName = storeName || pageName
    if (!compName) {
      console.warn(`${key}-存在未定义模块名的${storeName ? 'store' : 'page'}，为了不影响正常使用，请检查代码`)
    }
    caches[compName] = r(key).default || r[key]
  })
  return caches
}

// 打印
export const print = (id) => {
  const dom = document.getElementById(id).innerHTML
  var newwindow = window.open('', 'printBox')
  newwindow.document.write(dom.innerHTML)
  newwindow.window.print() // Firefox可以调用,IE没有效果
}

// 格式化文件列表
export const fileFormat = (file) => {
  let fileList = []
  if (Array.isArray(file)) {
    fileList = file
  } else {
    fileList = Array.of(file)
  }
  fileList = fileList.map(file => {
    if (file.response && file.response.code === Vue.prototype.$successCode) {
      return {
        name: file.name,
        url: file.response.data.url,
        type: getFileType(file.raw?.type),
        status: file.status
      }
    } else if (file.name) {
      return {
        name: file.name || file.url,
        url: file.url,
        type: file.type || '',
        status: file.status
      }
    } else {
      return {
        name: file.name || file.url,
        url: file.url,
        type: file.type || '',
        status: file.status
      }
    }
  })
  console.log(fileList)
  return fileList.filter(x => !!x)
}

export function birthDayFromIdNo (identityCard) {
  const len = (identityCard + '').length
  let strBirthday = ''
  if (len === 18) {
    strBirthday = identityCard.substr(6, 4) + '/' + identityCard.substr(10, 2) + '/' + identityCard.substr(12, 2)
  }
  if (len === 15) {
    let birthdayValue = ''
    birthdayValue = identityCard.charAt(6) + identityCard.charAt(7)
    if (parseInt(birthdayValue) < 10) {
      strBirthday =
        '20' + identityCard.substr(6, 2) + '/' + identityCard.substr(8, 2) + '/' + identityCard.substr(10, 2)
    } else {
      strBirthday =
        '19' + identityCard.substr(6, 2) + '/' + identityCard.substr(8, 2) + '/' + identityCard.substr(10, 2)
    }
  }
  return strBirthday
}

export function getAgeByNo (identityCard) {
  let strBirthday = ''
  strBirthday = birthDayFromIdNo(identityCard)
  const birthDate = new Date(strBirthday)
  const nowDateTime = new Date()
  let age = nowDateTime.getFullYear() - birthDate.getFullYear()
  if (
    nowDateTime.getMonth() < birthDate.getMonth() ||
    (nowDateTime.getMonth() === birthDate.getMonth() && nowDateTime.getDate() < birthDate.getDate())
  ) {
    age--
  }
  return age
}

export function sexFromIdNo (identityCard) {
  const a = identityCard.substring(identityCard.length - 2, identityCard.length - 1)
  const b = Number(a) % 2
  if (b % 2 === 1) {
    return '1'
  } else {
    return '0'
  }
}

/**
 * 判断值是否为空
 * @param {String|Number|Object|Array} value
 * @param {Boolean} allowBlank 允许空字符串
 */
export const isEmpty = (value, allowBlank) => value === null || value === undefined || (allowBlank ? false : value === '')

Vue.directive('watermark', (el, binding) => {
  const text1 = '小象湾托育中心'
  const time = new Date()
  // 当前日期的月日时分
  const text2 = (time.getMonth() + 1) + '' + time.getDate() + '' + time.getHours() + '' + time.getMinutes()
  const font = '12px Microsoft JhengHei'
  const textColor = 'rgba(192, 192, 192, 0.3)'
  // 根据两个文字的长度设置每一个模块的长度
  const width = text1.length > text2.length ? (text1.length * 12 + 40) : (text2.length * 12 + 40) || 150
  const height = 80
  // 倾斜角度
  const textRotate = -20

  function addWaterMarker (parentNode) {
    const can = document.createElement('canvas')
    parentNode.appendChild(can)
    can.width = width
    can.height = height
    can.style.display = 'none'
    const cans = can.getContext('2d')
    cans.rotate(textRotate * Math.PI / 180)
    cans.font = font
    cans.fillStyle = textColor
    cans.textAlign = 'left'
    cans.textBaseline = 'Middle'
    cans.fillText(text1, 0, height)
    // cans.fillText(text2, 0, height - 30)
    // 将水印返回成图片
    parentNode.style.backgroundImage = 'url(' + can.toDataURL('image/png') + ')'
  }

  addWaterMarker(el)
})

export function formatISODate (dateForm) {
  if (dateForm === '') {
    return ''
  } else {
    const dateee = new Date(dateForm).toJSON()
    const date = new Date(+new Date(dateee) + 8 * 3600 * 1000).toISOString().replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '')
    return date
  }
}

export function formatDate (date, fmt) {
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  }
  const o = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'h+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds()
  }
  for (const k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      const str = o[k] + ''
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str))
    }
  }
  return fmt
}

function padLeftZero (str) {
  return ('00' + str).substr(str.length)
}

import CryptoJS from 'crypto-js'
// 加密方法
export function encrypt (str, key) {
  return CryptoJS.AES.encrypt(str, key).toString()
}
// 解密方法
export function decrypt (ciphertext, key) {
  const bytes = CryptoJS.AES.decrypt(ciphertext, key)
  return bytes.toString(CryptoJS.enc.Utf8)
}
